// 市级代理
var db = require("../db/index");
var config = require("../_include/config");
var db_table_name = config.dbname.busMA;
var db_id_prefix = config.dbIdPrefix.busMA;
var helper = require("../_include/helper");

//构造函数
var _con = function(info) {
	var self = this;
	//ID编号
	self._id = db_id_prefix + Math.random().toString(16).substr(2) + (+new Date).toString(16);

	self.state = _con.STATE.审核通过;

	//所属的商家
	self.bus_id = info.bus_id;
	if (!self.bus_id) {
		throwCusError("市代必须指定一个所属商家")
	}

	if (!info.user_id && info.user_info) {
		var user = new UserCon(info.user_info);
		info.user_id = user._id;
	}
	//介绍人
	if (info.introducer) {
		var introducer = UserCon.search(info.introducer);
		if (!introducer) {
			throwCusError("无法根据指定信息找到相关介绍人，请输入电话号码或者邮箱");
		}
		this.introducer_id = introducer._id;
	}
	//拥有此市代身份的用户
	self.user_id = info.user_id;
	if (!self.user_id) {
		throwCusError("市代必须指定一个用户账号")
	}
	var user = UserCon.get(self.user_id);
	if (!user) {
		throwCusError("市代指定的用户账号无效")
	}
	if (user.isMAByBusId(self.bus_id)) {
		throwCusError("指定的用户账号已经是市代身份")
	}

	this.setRealInfo(info, "no_save");
	this.setInfo(info, "no_save");

	self.create_time = +new Date;

	user._setMA(self.bus_id, self._id);
	db.insert(db_table_name, self);
	console.log("创建了一个市级代理：", info.city_name);
};
//PS:模块的暴露放在require skill前面，因为二者互相依赖
module.exports = _con;
//技能
_con.prototype = require("./skill");

_con.STATE = {
	"未审核": 0,
	"审核中": 1,
	"审核通过": 2,
	"冻结": -1,
}

//静态方法
_con.get = function(Id) {
	var result = db.find_by_id(db_table_name, Id);
	return _con.getInstance(result);
};
_con.getInstance = function(obj) {
	if (obj) {
		if (!(obj.nojson_able_keys instanceof Array)) { //固定黑名单
			Object.defineProperty(obj, "nojson_able_keys", {
				enumerable: false,
				value: ["joiner_map"]
			});
		}
		obj.__proto__ = _con.prototype;
	}
	return obj;
};
_con.login = function(login_info) {
	// body...
}

var UserCon = require("../user/_con");
var BusCon = require("../bus/_con");